package cn.kevinkun.QRCode;

import java.io.IOException;

import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.UsesAssets;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.AndroidNonvisibleComponent;
import com.google.appinventor.components.runtime.Component;
import com.google.appinventor.components.runtime.ComponentContainer;
import com.google.appinventor.components.runtime.HVArrangement;

import android.content.Context;
import android.graphics.Color;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

@DesignerComponent(version = 1, category = ComponentCategory.EXTENSION, description = "http://www.kevinkun.cn", iconName = "images/extension.png", nonVisible = true, helpUrl = "")
@SimpleObject(external = true)
@UsesAssets(fileNames = "qrcode.html, qrcode.min.js")
public class KevinkunQRCode extends AndroidNonvisibleComponent implements Component {
	Context context;
	WebView webView;
	String code = "";

	public KevinkunQRCode(ComponentContainer container) {
		super(container.$form());
		this.context = container.$context();
	}

	WebViewClient webViewClient = new WebViewClient() {
		public void onPageFinished(WebView view, String url) {
			webView.evaluateJavascript(code, null);
		}
	};

	@SimpleFunction(description = "")
	public void MakeQRCode(HVArrangement layout, String text, int size) {

		ViewGroup viewGroup = (ViewGroup) layout.getView();
		viewGroup.removeAllViews();
		webView = new WebView(context);
		viewGroup.addView(webView);

		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(webViewClient);

		layout.Height(size + 20);
		layout.Width(size + 20);

		code = "makeCode('" + text + "'," + size + ")";

		try {
			webView.loadUrl(this.form.getAssetPathForExtension(this, "qrcode.html"));
		} catch (IOException localIOException) {

		}
	}

	//copy and adopt from com.appybuilder.lukehoogenboom.Colour extension 
	public String ARGBToHex(int argbColor) {
		int alpha = Color.alpha(argbColor);
		int red = Color.red(argbColor);
		int green = Color.green(argbColor);
		int blue = Color.blue(argbColor);
		return String.format("#%02x%02x%02x%02x", new Object[] { Integer.valueOf(red), Integer.valueOf(green),
				Integer.valueOf(blue), Integer.valueOf(alpha) });
	}

}
